<?php
/**
 * 腾讯云省市区数据抓取
 */
namespace app\admins\controller\test;
use \think\Controller;
class Area extends Controller {
    
    public function __construct(){
        exit('数据抓取完成');
    }
    
    public function index(){
        $arealist = $this->getSub(1);
        $this->assign(get_defined_vars());
        return $this->fetch();
    }
    
    
    public function getSub($pid){
        $page = 1;
        $list = M("tx_area")->where(['level'=>4])->limit(1000)->page($page)->order('tid asc')->select();
        dump($list);exit;
        return $list;
    }
    
    
    public function save(){      
        exit(); // 6page 已经处理
        try{        
            $data = $_POST;
            $pcode  = rtrim($data['id'],'0');        
            $level  = ceil( strlen($pcode)/2 );
            $fcode = substr($pcode,0,$level*2-2);
            if( $fcode ){
                $w = 6-strlen($fcode);
                for( $i ;$i<$w ;$i++ ){
                   $fcode = $fcode.'0';
                }
            }else{
                $fcode = 0;
            }
            
            if($data['pid']){
                $fcode = $data['pid'];
                $level = 4;
            }
            
            $saveData = array(
                'tid'    =>  $data['id'],
                'pid'   =>  $fcode,
                'level'  => $level,
                'name'   => $data['name'],
                'fullname' => $data['fullname'],
               // 'pinyin'    => implode(' ',$data['pinyin']),
                'lat'       => $data['location']['lat'],
                'lng'       => $data['location']['lng'],
                //'cidx'      => implode(',',$data['cidx'])
            );
            if( $data['cidx'] ) $saveData['cidx'] = $data['cidx'];
            if( is_array( $data['cidx'])) $saveData['cidx'] = implode(',',$data['cidx']);
            
            if( $data['pinyin'] ) $saveData['pinyin'] = $data['pinyin'];
            if( is_array( $data['pinyin'])) $saveData['pinyin'] = implode(' ',$data['pinyin']);
            
            
            $id = $this->saveD($saveData); 
            exit(json_encode(['id'=>$id]));
        }catch(\think\Exception $e){
            exit(json_encode(['id'=>0,'error'=>$e->getMessage()]));
        }
        
    }
    
    private function saveD($data){
        try{
            $id = M("tx_area")->insertGetId($data);
            return $id;
        }catch(\think\Exception $e){
            $save = cache('areaSaveErr');
            $save = unserialize($save);
            if(!$save) $save = [];
            $save[] = $data;
            cache('areaSaveErr',serialize($save));
            return 0;
        }        
    }
    
    public function show(){
        $save = cache('areaSaveErr');
        $save = unserialize($save);
        dump($save);
    }

}